#include "mainwindow.h"
#include "ui_mainwindow.h"


boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query("xxx.xxx.xxx.xxx", "3200");
tcp::resolver::iterator myiterator =resolver.resolve(query);
chat_client c(io_service, myiterator);
boost::thread t;
char line[chat_message::max_body_length + 1];

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    qRegisterMetaType< std::string >("std::string");
    connect (&c,SIGNAL(messageShow(const std::string &)),this,SLOT(messageShow(const std::string &)));
    connect(ui->lineEdit_message_to_send, SIGNAL(returnPressed()),ui->pushButton_send_message,SIGNAL(clicked()));
    t=boost::thread(boost::bind(&boost::asio::io_service::run, &io_service));
}

MainWindow::~MainWindow()
{
    c.close();
    delete ui;
}

void MainWindow::on_pushButton_send_message_clicked()
{
    string nickname =ui->lineEdit_nick_name->text ().toStdString ();
    string  message =ui->lineEdit_message_to_send->text ().toStdString ();
    strcpy (line,(nickname+":"+message).c_str ());
    using namespace std; // For strlen and memcpy.
    chat_message msg;
    msg.body_length(strlen(line));
    memcpy(msg.body(), line, msg.body_length());
    msg.encode_header();
    c.write(msg);
    ui->lineEdit_message_to_send->clear ();
}

/**
 * @brief MainWindow::on_pushButton_clicked
 *  connect to server
 */
void MainWindow::on_pushButton_clicked()
{

}

void MainWindow::messageShow(const string &message)
{
    QString qstr = QString::fromStdString(message);
    ui->textEdit_show_message->append (qstr);
    ui->textEdit_show_message->ensureCursorVisible ();
}


